<template>
  <div>
    <vxe-modal v-model="dialogVisible" ref="modal" title="新增检测项目" :position="{ top: 'center', left: 'center' }"
      width="90%" :before-hide-method="clear" :destroy-on-close="true">
      <vxe-form :data="form" title-align="right">

        <vxe-form-item title="收费标准" :field="isContractPrice ? 'infoName' : 'versionName'" :item-render="{}">
          <template #default="{ data }">
            <vxe-input v-model="data[isContractPrice ? 'infoName' : 'versionName']" class="normal" placeholder="检测标准名称"
              clearable readonly :disabled="!isContractPrice && !!infoId" @click="openStd"></vxe-input>
          </template>
        </vxe-form-item>

        <vxe-form-item title="检测项目" field="itemName" :item-render="{}">
          <template #default="{ data }">
            <vxe-input v-model="data.itemName" class="normal" placeholder="检测项目名称" clearable
              :disabled="!!itemName"></vxe-input>
          </template>
        </vxe-form-item>


        <vxe-form-item title="" field="" :item-render="{}">
          <template>
            <vxe-button status="primary" icon="vxe-icon-search" size="small" title="搜索" @click="search"></vxe-button>
            <vxe-button status="info" icon="vxe-icon-indicator" size="small" title="重置" @click="reset"></vxe-button>
          </template>
        </vxe-form-item>
      </vxe-form>

      <vxe-grid class="table-tree" ref="table" resizable show-overflow row-key :key="timer" maxHeight="400" keep-source
        size="small" border="inner" :data="transTableData" :tree-config="{
          line: true,
          transform: true,
          parentField: 'parentTag',
          children: 'paramList',
          rowField: 'tag',
          iconOpen: '',
          iconClose: 'vxe-icon-square-plus',
        }" v-bind="isEdit ? configOptions : null" :row-config="{ isHover: true, isCurrent: true, keyField: 'paramId' }"
        :scroll-y="{ enabled: false }" :columns="columns" :checkbox-config="{
          trigger: isEdit ? 'cell' : 'row',
          checkRowKeys: checkRowids,
          showHeader: type === 'radio' ? false : true,
        }" @checkbox-change="changeSelect" @checkbox-all="changeSelect">
        <template #d_itemName="{ row }">
          <template v-if="!row.parentTag">
            <i :class="$refs.table.isTreeExpandByRow(row) ? 'vxe-open_file' : 'vxe-close_file'"></i>
          </template>
          <template v-else>
            <i class="vxe-circle"></i>
          </template>
          <span>{{ !row.parentTag ? row.itemName : row.paramName }}</span>
        </template>
        <template #e_itemName="scope">
          <template v-if="!scope.row.parentTag">
            <i :class="$refs.table.isTreeExpandByRow(scope.row) ? 'vxe-open_file' : 'vxe-close_file'"></i>
          </template>
          <template v-else>
            <i class="vxe-circle"></i>
          </template>
          <vxe-input v-if="!scope.row.parentTag" v-model="scope.row.itemName" type="text"></vxe-input>
          <vxe-input v-else v-model="scope.row.paramName" type="text"></vxe-input>
        </template>
        <template #d_detectionStdList="scope">
          <span>{{ scope.row.detectionStdList | getDetectionStdList }}</span>
        </template>

        <template #e_detectionStdList="scope">
          <vxe-input :value="scope.row.detectionStdList | getDetectionStdList" type="text" readonly placeholder="检测标准"
            clearable @clear="clearDetectionStdList(scope.row)" @click="openDetectionStd(scope.row)"></vxe-input>
        </template>

      </vxe-grid>
      <!-- <vxe-pager
      background
      :current-page.sync="form.page"
      :page-size.sync="form.pageSize"
      :total="total"
      :layouts="['Total', 'Sizes', 'PrevPage', 'JumpNumber', 'NextPage']"
      @page-change="change"
    >
    </vxe-pager> -->
      <div slots="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </div>
    </vxe-modal>

    <SelectFromTableDialog ref="std" title="收费标准列表" type="radio" :searchConfig="curSearchConfig" append-to-body
      width="50%" :columns="curColumns" :tableData="chargeStdList" :total="stdTotal" @pager="searchStd"
      @search="searchStd" @submit="getStd" />
    <SelectFromTableDialog ref="selectStd" v-model="curRow.detectionStdList" :searchConfig="detSearchConfig"
      :tableData="stdList" :total="detTotal" type="radio" :columns="stdColumn" title="选择检测标准" @pager="curEvent"
      @search="curEvent" @submit="selDetStd" />
  </div>
</template>
<script>
import { arrayToTree } from '/@/util/util';
import VXETable from 'vxe-table';
import SelectFromTableDialog from '../SelectFromTableDialog';
export default {
  components: {
    SelectFromTableDialog,
  },
  props: {
    columns: {
      type: Array,
      default: () => [],
    },
    tableData: {
      type: Array,
      default: () => [],
    },
    total: {
      type: [String, Number],
      default: 10,
    },
    value: {
      type: Array,
      default: () => [],
    },
    type: {
      type: String,
      default: 'checkbox',
    },
    isContractPrice: {
      type: Boolean,
      default: false,
    },
    contractId: {
      type: [String, Number],
      default: '',
    },
    infoId: {
      type: [String, Number],
      default: '',
    },
    // 传入itemName表示要固定搜索检测参数
    itemName: {
      type: String,
      default: '',
    },
    isEdit: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      dialogVisible: false,
      form: {
        itemName: '',
        infoName: '',
        versionName: '',
        page: 1,
        size: 10,
      },
      childForm: {
        infoName: '',
        versionName: '',
        isEnabled: true,
        page: 1,
        size: 10,
      },
      stdColumns: [
        {
          type: 'radio',
          title: '',
          width: 60,
          editRender: {},
        },
        {
          field: 'versionName',
          title: '收费标准版本号',
          editRender: {},
        },
      ],
      stdSearchConfig: [
        {
          label: '收费标准版本号',
          field: 'versionName',
        },
      ],
      stdContractColumns: [
        {
          type: 'radio',
          title: '',
          width: 60,
          editRender: {},
        },
        {
          field: 'infoName',
          title: '收费标准版本号',
          editRender: {},
        },
      ],
      stdContractSearchConfig: [
        {
          label: '收费标准版本号',
          field: 'infoName',
        },
      ],
      stdColumn: [
        {
          type: 'radio',
          title: '',
          width: 60,
          editRender: {},
        },
        {
          field: 'dictValue',
          title: '检测标准',
          editRender: {},
        },
      ],
      detSearchConfig: [
        {
          label: '检测标准名称',
          field: 'dictValue',
        },
      ],
      chargeStdList: [],
      stdTotal: 0,
      result: [],
      stdList: [],
      detTotal: 0,
      curRow: {
        detectionStdList: [],
        detectionStdIds: [],
      },
      configOptions: {
        'edit-config': {
          trigger: 'click',
          mode: 'cell',
          showIcon: false,
          activeMethod: this.activeCellMethod,
        },
        'edit-rules': {
          detectionStdList: [
            {
              required: true,
              validator: ({ row }) => {
                if (!!row.parentTag && (!row.detectionStdList || row.detectionStdList.length === 0)) {
                  return new Error('请选择检测标准');
                }
              },
            },
          ],
        },
      },
      timer: Date.now(),
    };
  },
  filters: {
    getDetectionStdList(list) {
      if (!list) return;
      return list?.map((item) => item.dictValue)?.join('、');
    },
  },
  watch: {
    dialogVisible(val) {
      if (val) {
        this.result = [...this.value];
      }
    },
    async contractId() {
      await this.selFirstStd();
    },
    itemName(val) {
      this.form.itemName = val;
    },
  },
  computed: {
    transTableData() {
      // 每次更新table数据时刷新treeTable，才能默认选中
      !this.flag && (this.timer = Date.now() + '');
      function flatten(arr = [], parent = {}, dep = 1) {
        return arr.reduce((prev, item) => {
          item.tag = this.isContractPrice && dep === 1 ? item.itemId : item.id;
          item.parentTag = parent.tag;
          item.paramId = item.paramId || item.id;
          item.itemId = item.itemId || item.id;
          // 新增字段需要进行监听
          this.$set(item, 'detectionStdList', item.detectionStdList || []);
          this.$set(item, 'detectionStdIds', item.detectionStdIds || []);
          return prev.concat(item, flatten.call(this, item.chargeStdParamList || [], item, 2));
        }, []);
      }
      const result = flatten.call(this, this.tableData);
      this.flag = false;
      return result;
    },
    checkRowids() {
      return this.result
        .map((item) => item.chargeParamList)
        .flat(1)
        .map((item) => item.paramId);
    },
    curColumns() {
      return this.isContractPrice ? this.stdContractColumns : this.stdColumns;
    },
    curSearchConfig() {
      return this.isContractPrice ? this.stdContractSearchConfig : this.stdSearchConfig;
    },
    curEvent() {
      return this.isContractPrice ? this.getContractStdList : this.getStdList;
    },
  },
  methods: {
    async selFirstStd() {
      await this.getChargeStd();
      if (this.chargeStdList.length === 0) return;
      this.getStd(this.chargeStdList[0]);
    },
    activeCellMethod({ column, row }) {
      if (!row.parentTag) {
        return false;
      }
      if (column.field === 'detectionStdList') {
        return true;
      }
    },
    changeSelect(data) {
      console.log(data, 666)
      let records = data.records;
      if (this.type === 'radio') {
        records = data.records.filter((item) => item.itemId === data.row.itemId);
      }
      // 获取半选中的父级
      const halfChecked = this.$refs.table.getCheckboxIndeterminateRecords();
      // 整合成完整的一维数组
      const result = [...halfChecked, ...records];
      // 整合成树
      const tree = result
        ?.filter((item) => !item.parentTag)
        ?.map((item) => {
          return {
            ...item,
            chargeParamList: arrayToTree(result, item.tag, 'parentTag'),
          };
        });
      // 单选的话直接获取最后一条数据
      if (this.type === 'radio') {
        this.result = tree.slice(-1);
        this.$refs.table.setAllCheckboxRow(false);
        this.$refs.table.setCheckboxRow(records, true);
        return;
      }
      this.result = [
        ...this.result.filter(
          (item) => tree.every((it) => item.itemId !== it.itemId) && item.itemId !== data.row.itemId,
        ),
        ...tree,
      ];
    },
    search() {
      this.form.page = 1;
      this.$emit('search', this.form);
    },
    reset() {
      this.resetPage();
      this.$emit('search', this.form);
    },
    clear() {
      this.$refs.table.clearCheckboxRow();
      this.dialogVisible = false;
      this.reset();
    },
    async selectValidEvent() {
      const $table = this.$refs.table;
      const selectRecords = $table.getCheckboxRecords();
      console.log(selectRecords, 'tree')
      if (selectRecords.length > 0) {
        const errMap = await $table.validate(selectRecords).catch((errMap) => errMap);
        if (errMap) {
          VXETable.modal.message({ status: 'error', content: '校验不通过！' });
          return;
        } else {
          VXETable.modal.message({ status: 'success', content: '校验成功！' });
          console.log(this.result, 666)
          this.$emit('submit', [...this.result]);
          this.clear();
        }
      } else {
        VXETable.modal.message({ status: 'warning', content: '未选中数据！' });
        return;
      }
    },
    async submit() {
      this.selectValidEvent();
    },
    change({ type, currentPage, pageSize }) {
      this.form.page = currentPage;
      this.form.size = pageSize;
      this.$emit('pager', this.form);
    },
    // 重置参数
    resetPage() {
      this.form.itemName = this.itemName || '';
      this.form.page = 1;
      this.form.size = 10;
    },
    openStd() {
      this.$refs.std.dialogVisible = true;
    },
    async getChargeStd(params) {
      await (this.isContractPrice ? this.getChargeStdList(params) : this.getChargeStdPage(params));
    },
    async getChargeStdPage(params = { isEnabled: true, page: 1, size: 10 }) {
      await this.$api.getChargeStdPage({ infoId: this.infoId, ...params }).then((res) => {
        this.chargeStdList = res.data.list;
        this.stdTotal = res.data.total;
      });
    },
    async getChargeStdList(params = { isEnabled: true, page: 1, size: 10 }) {
      await (this.contractId &&
        this.$api.getChargeStdList({ ...params, contractId: this.contractId }).then((res) => {
          this.chargeStdList = res.data;
        }));
    },

    searchStd(params) {
      const { versionName, infoName, page, size } = params;
      this.childForm.versionName = versionName;
      this.childForm.infoName = infoName;
      this.childForm.page = page;
      this.childForm.size = size;
      this.getChargeStd(this.childForm);
    },
    getStd(data) {
      this.form.versionName = data?.versionName;
      this.form.infoName = data?.infoName;
      this.form.infoId = data?.infoId || data?.id;
      this.$emit('refreshStd', this.form);
    },
    resetModal() { },
    async getStdList(params = { page: 1, size: 10 }) {
      await this.$api.getStdList({ ...params, isEnabled: true }).then((res) => {
        const { list, total } = res.data;
        this.stdList = list;
        this.detTotal = total;
      });
    },
    getContractStdList(params) {
      this.stdList = this.storeStdList.filter((item) => {
        return !params.dictValue || item.dictValue.includes(params.dictValue);
      });
      this.detTotal = this.stdList.length;
    },
    openDetectionStd(row) {
      this.curRow = row;
      this.flag = true;
      if (this.isContractPrice) {
        this.stdList = row.detectRelaList.map((item) => {
          const { detectId: id, detectName: dictValue } = item;
          return {
            id,
            dictValue,
          };
        });
        this.storeStdList = [...this.stdList];
        this.detTotal = this.stdList.length;
      } else {
        this.getStdList();
      }
      this.$refs.selectStd.dialogVisible = true;
    },
    clearDetectionStdList(row) {
      row.detectionStdList = [];
    },
    selDetStd(params) {
      this.curRow.detectionStdList = [params];
      this.curRow.detectionStdIds = [params.id];
      this.$refs.table.setCheckboxRow(this.curRow, false)
      console.log(this.curRow, this.result, 998877)
      // if (this.result.length > 0) {
      //   this.result = this.result[0].chargeParamList.filter(item => item.id !== this.curRow.id)
      // }

      this.$refs.selectStd.dialogVisible = false;
    },
  },
};
</script>
<style lang="scss" scoped>
::v-deep {
  .table-normal .vxe-body--row .vxe-body--column {
    height: 40px !important;
  }

  .vxe-modal--box {
    position: absolute;
    left: 50% !important;
    top: 50% !important;
    transform: translate(-50%, -50%) !important;
  }

  .hidden {
    display: none !important;
  }

  .show {
    display: block !important;
  }
}
</style>
